// subPages/health/recordSugar/record.js
const app = getApp()
var util =  require('../../../utils/util.js');
var dateTimePicker = require('../../../utils/dateTimePicker.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ["请选择测量点","早餐前","早餐后","午餐前","午餐后","晚餐前","晚餐后"],
    index:0,
    downImg:'/resources/index/down.png',
    upImg: '/resources/index/up.png',
    bloodData: '0.0',
    symbol: '<',
    pBtnTxt:{
      pBtnTxt: '保存'
    },
    dateTimeArray: null,
    dateTime: null,
    startYear: 2000,
    endYear: 2050,
    id: '',
    isInput: false,
    isSave: true,
    readText:'读取',
    isCheckImg: '/resources/index/uncheck.png',
    isCheck: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      timePointImgsrc:this.data.downImg,
      date: util.setTime11(new Date())
    })
    this.getCont()
  },

  //获得数
  getCont:function(){
    var that = this
    wx.request({
      url: app.globalData.apiUrl +'/get_user_xuetang_num',
      data: {
        userid: app.globalData.userId,
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        that.setData({
          readCount: res.data
        })
      },
      fail: function (res) {
        console.log("失败",res);
      }
    })
  },

  //改变input
  inputBtn:function(){
    var that = this    
    if(that.data.isSave == false){
      util.showModal('提示','请保存读取的数据')
      return
    }
    that.setData({
      isInput: true,
      readText: '完成'
    })
  },

  readInput:function(e){
    this.setData({
      bloodData : e.detail.value
    })
    // console.log(this.data.bloodData)
  },

  //picker
  bindTimePointChange: function (e) {
    this.setData({
      index: e.detail.value,
      timePoint: this.data.array[e.detail.value],
      timePointImgsrc: this.data.downImg,
    })
  },
  
  bindTimePointCancel:function(){
    this.setData({
      timePointImgsrc: this.data.downImg
    })
  },

  bindTextArea:function(e){
    this.setData({
      textArea: e.detail.value
    })
  },

  //选择箭头
  imgChange:function(e)
  {
    var that = this
    if(that.data.timePointImgsrc == that.data.downImg)
    {
      that.setData({
        timePointImgsrc: that.data.upImg
      })
    }
  },
  

  //读取按钮
  readBtn:function(e){
    var that = this
    var text = e.currentTarget.dataset.text
    if(text == '读取'){
      if(that.data.readCount == 0) {
        util.showModal('提示','当前用户没有可读取的数据')
        return
      }
      if(that.data.isInput) {
        util.showModal('提示','请保存自定义数据')
        return
      }
      if(!that.data.isSave){
        util.showModal('提示','请保存读取的数据')
        return
      }
      wx.request({
        url: app.globalData.apiUrl +'/get_xuetang_list',
        data: {
          userid: app.globalData.userId
        },
        method: 'get',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          that.setData({
            isSave: false,
            bloodData: res.data.blood,
            id: res.data.id,
            date: res.data.addtime.substring(0,16),
            readCount: that.data.readCount-1
          })
        },
        fail: function (res) {
          console.log("失败",res);
        }
      })
    }else if(text == '完成'){
      that.setData({
        readText: '读取'
      })
    }
  },

  //是否异常
  isAbnormal:function(e){
    var that = this
    var isCheck = e.currentTarget.dataset.check
    that.setData({
      isCheck: !isCheck
    })
  },

  //改变日期格式转数组
  changeTime:function(dateTime){
    let date = dateTime.substring(0,10)
    let dateList= date.split('-')
    let dateTimeArr = []
    for(let i in dateList)
    {
      if(dateList[i].length==4){
        let Y =dateList[i].substring(2,4)
        dateTimeArr.push(parseInt(Y))
      }else{
        let md = (dateList[i].substring(0,2)) - 1
        dateTimeArr.push(md)
      }
    }
    let time = dateTime.substring(11,17)
    let timeList = time.split(':')
    for(let j in timeList)
    {
      dateTimeArr.push(parseInt(timeList[j]))
    }
    return dateTimeArr
  },  

  //改变数组转日期格式
  changeTime2:function(dateTime){
    // console.log(dateTime)
    var Y1 = (util.setTime10(new Date())).substring(0,2)
    var Y = Y1 + dateTime[0]
    let M = util.change(parseInt(dateTime[1]) + 1)
    let D = util.change(parseInt(dateTime[2]) + 1)
    let H = util.change(dateTime[3])
    let m = util.change(dateTime[4])
    return Y + '-' + M + '-' + D + ' ' + H + ':' + m
  },

  //判断数据
  judgmentValue:function(){
    var that = this
    if(that.data.timePoint == '' || that.data.timePoint == '请选择测量点'){
      util.showModal('提示','请选择测量点')
      return false;
    }
    if(that.data.bloodData === '0.0' || that.data.bloodData == ''){
      util.showModal('提示','请读取或输入血糖值')
      return false;
    }
    if(that.data.bloodData.length > 0){
      let type= 'number'
      let validation = util.validation(that.data.bloodData,type)
      if(!validation){
        util.showModal('提示','血糖值输入不正确')
        return false;
      }
    }
    return true
  },


  //转换时间
  changeTime3:function(){
    var that = this
    if(that.data.isInput){
      addtime = that.changeTime2(that.data.dateTime)
    }
    else{
      addtime = that.data.date
    }
  },

  //保存
  lickBtn:function(){
    var that = this
    let type =  that.typeConversion(that.data.timePoint);
    if(type == 0){
      util.showModal('提示','请选择测量点')
      return;
    }
    var judgmentValue = that.judgmentValue();
    if(!judgmentValue) return;
    var textArea = that.data.textArea?that.data.textArea: ''
    if(that.data.id){
      //有数据id
      wx.request({
        url: app.globalData.apiUrl +'/user_record_xuetang',
        data: {
          id: that.data.id,
          userid: app.globalData.userId,
          type: type,
          blood: that.data.bloodData,
          content: textArea
        },
        method: 'post',
        header: {
          'content-type': 'application/x-www-form-urlencoded' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            that.setData({
              id: '',
              bloodData: '0.0',
              isSave: true,
              isInput: false,
              textArea: '',
              date: util.setTime11(new Date()),
              index: 0,
              timePoint: '请选择测量点',
            })
          }else{
            util.showModal('提示','保存失败，请重新保存')
            return;
          }
        },
        fail: function (res) {
          console.log("失败",res);
        }
      })
    }else{
      if(that.data.isInput){
        var addtime = that.changeTime2(that.data.dateTime) + ':00'
        var date = addtime.substring(0,10)
        var time = addtime
        time = time.replace(/-/g, '/');
        var createtime =  Date.parse(new Date(time))/1000
      }
      wx.request({
        url: app.globalData.apiUrl +'/user_record_xuetang',
        data: {
          userid: app.globalData.userId,
          type: type,
          blood: that.data.bloodData,
          content: textArea,
          date: date,
          addtime: addtime,
          createtime: createtime
        },
        method: 'post',
        header: {
          'content-type': 'application/x-www-form-urlencoded' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            that.setData({
              id: '',
              bloodData: '0.0',
              isSave: true,
              isInput: false,
              textArea: '',
              date: util.setTime11(new Date()),
              index: 0,
              timePoint: '请选择测量点',
            })
            util.showToast('保存成功','success')            
          }else{
            util.showModal('提示','保存失败，请重新保存')
            return;
          }
        },
        fail: function (res) {
          console.log("失败",res);
        }
      })
    }
  },

  //测量时间点类型转换
  typeConversion:function(type){
    if(type == '早餐前'){
      return 1
    }
    if(type == '早餐后'){
      return 2
    }
    if(type == '午餐前'){
      return 3
    }
    if(type == '午餐后'){
      return 4
    }
    if(type == '晚餐前'){
      return 5
    }
    if(type == '晚餐后'){
      return 6
    }else{
      return 0 
    }
  },

  //选择时间方法
  changeDateTime(e) {
    this.setData({
      dateTime: e.detail.value
    });
  },

  changeDateTimeColumn(e) {
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN健康管理',
      path: 'pages/index/index',
      success: function(res) {
        // res.shareTickets 
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})